package main

import (
	"bytes"
	"fmt"
	"net/http"

	log "github.com/sirupsen/logrus"
)

type Requester struct {
	// req http.Request
	config RequesterConfig
}

func NewRequester(config RequesterConfig) (*Requester, error) {
	req := Requester{
		config: config,
	}
	return &req, nil
}

func (r *Requester) Request(payload []byte) error {
	method := r.config.Method
	url := r.config.URL
	buf := []byte(payload)
	body := bytes.NewReader(buf)
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return err
	}
	header := r.config.Headers
	req.Header = header
	req.Header.Set("User-Agent", "curl")
	res, err := http.DefaultClient.Do(req)
	log.WithFields(log.Fields{"res": res, "err": err}).Info("request result")
	if err != nil {
		return err
	}
	defer req.Body.Close()
	if res.StatusCode >= 200 && res.StatusCode < 400 {
		return nil
	}
	return fmt.Errorf("request failed: %s", res.Status)
}
